# encoding: utf-8
import os

from datetime import datetime
from google.appengine.api import users
from google.appengine.api import mail
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template

import models
import base_def
import memcache_def

class BaseRequestHandler(webapp.RequestHandler):
	"""Base classs"""
	def __init__(self):
		self.settings = base_def.wgw_change_setting(memcache_def.get_setting_memcache())
		#if len(self.settings) < 6:
		#	base_def.add_setting('comment_per_page','8','comment_per_page','int')
		#	memcache_def.update_setting_memcache()
		self.pages = memcache_def.get_page_memcache()
	def generate(self, template_name, template_values={}):
		categorys = memcache_def.get_category_memcache()
		news_comments = memcache_def.get_comment_memcache(self.settings['count_rec_comments'])
		cundang = memcache_def.get_cundang_memcache()
		links = memcache_def.get_link_memcache()
		values = {
			'categorys': categorys,
			'news_comments': news_comments,
			'cundang': cundang,
			'links': links,
			'settings': self.settings,
			'pages': self.pages
		}
		values.update(template_values)
		directory = os.path.dirname(__file__)
		path = os.path.join(directory, os.path.join('templates', template_name))
		self.response.out.write(template.render(path, values))

class default(BaseRequestHandler):
	def get(self):
		bookmark_id = self.request.get('b')
		if bookmark_id:
			time_date_page = models.Article.get_by_id(int(bookmark_id)).time_date
			articles = models.Article.all().order('-time_date').filter('time_date <=',time_date_page).filter('article_type','article').fetch(limit=self.settings['count_per_page']+1)
			pre_articles = models.Article.all().order('time_date').filter('time_date >',time_date_page).filter('article_type','article').fetch(limit=self.settings['count_per_page'])
		else:
			articles = models.Article.all().order('-time_date').filter('article_type','article').fetch(limit=self.settings['count_per_page']+1)
			pre_articles = None
		for article in articles:
			article.key_id = article.key().id()
			#帖子的分类
			cate_list = []
			for cat_key in article.categories_keys:
				cate_list.append(db.get(cat_key))
			article.category = cate_list
			#帖子的分类 END
		values_posts={
			'articles': articles[:self.settings['count_per_page']],
			'path': self.request.path
		}
		if len(articles) == self.settings['count_per_page']+1:
			values_page = {
				'next_page': articles[self.settings['count_per_page']]
			}
			values_posts.update(values_page)
		if (pre_articles) and (len(pre_articles)>0):
			values_pre_page = {
				'pre_page': pre_articles[-1]
			}
			values_posts.update(values_pre_page)
		self.generate('main_sidebar_base.html',values_posts)

class article(BaseRequestHandler):
	def get(self,value=None):
		article_id = self.request.path[1:-13]
		article = models.Article.get_by_id(int(article_id))
		user = users.get_current_user()
		# 获取评论
		b_c = self.request.get('b')
		if b_c:
			time_date_b_c = models.Comment.get_by_id(int(b_c)).time_date
			comments = models.Comment.all().filter('article', article).order('-time_date').filter('time_date <=',time_date_b_c).fetch(limit=self.settings['comment_per_page']+1)
			pre_comments = models.Comment.all().filter('article', article).order('time_date').filter('time_date >',time_date_b_c).fetch(limit=self.settings['comment_per_page'])
		else:
			comments = models.Comment.all().filter('article', article).order('-time_date').fetch(limit=self.settings['comment_per_page']+1)
			pre_comments = None
		# 获取评论 END
		cate_list = []
		for cate_key in article.categories_keys:
			cate_list.append(db.get(cate_key))
		article.categories = cate_list
		pre_article = models.Article.all().filter('article_type in',['article','page']).filter('time_date <',article.time_date).order('-time_date').get()
		lat_article = models.Article.all().filter('article_type in',['article','page']).filter('time_date >',article.time_date).order('time_date').get()
		value = {
			'article': article,
			'login_url': users.create_login_url(self.request.uri),
			'logout_url': users.create_logout_url(self.request.uri),
			'user': user,
			'pre_article': pre_article,
			'lat_article': lat_article,
		}
		# 评论分页
		if comments:
			value_c = {
				'comments': reversed(comments[:self.settings['comment_per_page']]),
				'path': self.request.path
			}
			value.update(value_c)
		if len(comments) == self.settings['comment_per_page']+1:
			value_comment = {
				'next_page': comments[self.settings['comment_per_page']]
			}
			value.update(value_comment)
		if (pre_comments) and (len(pre_comments)>0):
			value_pre_comment = {
				'pre_page': pre_comments[-1]
			}
			value.update(value_pre_comment)
		# 评论分页 END
		self.generate('article_sidebar_base.html',value)

	def post(self):
		user = users.get_current_user()
		if user:
			article_id = self.request.path[1:-13]
			url = self.request.get('url')
			alert_email = self.request.get('alert_email_checkbox')
			article = models.Article.get_by_id(int(article_id))
			content = self.request.get('content_comment_form')
			nickname = self.request.get('nickname_form')
			new_comment = models.Comment(article=article,user=user,nickname=nickname,content=content,url=url)
			new_comment.put()
			if alert_email:
				alert_email = user.email()
				cunzai = 0
				list_email = new_comment.article.alert_emails
				for email_it in list_email:
					if email_it == alert_email:
						cunzai += 1
				if cunzai==0:
					list_email.append(alert_email)
					new_comment.article.alert_emails = list_email
					new_comment.article.put()
			if new_comment.article.alert_emails:
				mail.send_mail(
					sender="bwanglei@gmail.com",
					to="bwanglei@gmail.com",
					bcc=new_comment.article.alert_emails,
					subject=new_comment.nickname+u'在《'+article.title+u'》发表了新评论',
					body=new_comment.content+'\n'+self.request.url
				)
			else:
				mail.send_mail(
				sender="bwanglei@gmail.com",
				to="bwanglei@gmail.com",
				subject=new_comment.nickname+u'在《'+article.title+u'》发表了新评论',
				body=new_comment.content+'\n'+self.request.url
			)
			memcache_def.update_comment_memcache(self.settings['count_rec_comments'])
			self.redirect('/'+str(article.key().id())+'_article.html#'+str(new_comment.key().id()))
		else:
			self.redirect(self.request.uri)

class category(BaseRequestHandler):
	def get(self):
		bookmark_id = self.request.get('b')
		category_id = self.request.path[1:-14]
		category_key = models.Category.get_by_id(int(category_id)).key()
		if bookmark_id:
			bookmark_time_date = models.Article.get_by_id(int(bookmark_id)).time_date
			articles = models.Article.all().filter('categories_keys =',category_key).filter('article_type','article').order('-time_date').filter('time_date <=',bookmark_time_date).fetch(limit=self.settings['count_per_page']+1)
			pre_articles = models.Article.all().filter('categories_keys =',category_key).filter('article_type','article').order('time_date').filter('time_date >',bookmark_time_date).fetch(limit=self.settings['count_per_page'])
		else:
			articles = models.Article.all().filter('categories_keys =',category_key).filter('article_type','article').order('-time_date').fetch(limit=self.settings['count_per_page']+1)
			pre_articles = None
		for article in articles:
			article.key_id = article.key().id()
			article.time_date_g = datetime.strftime(article.time_date,'%A %H:%M:%S %m月%d日 %Y年') #格式化帖子的发表时间
			#帖子的分类
			cate_list = []
			for cat_key in article.categories_keys:
				cate_list.append(db.get(cat_key))
			article.category = cate_list
			#帖子的分类 END
		values_posts={
			'articles': articles[:self.settings['count_per_page']],
			'path': self.request.path,
			'category_now': models.Category.get_by_id(int(category_id))
		}
		if len(articles) == self.settings['count_per_page']+1:
			values_page = {
				'next_page': articles[self.settings['count_per_page']]
			}
			values_posts.update(values_page)
		if (pre_articles) and (len(pre_articles)>0):
			values_pre_page = {
				'pre_page': pre_articles[-1]
			}
			values_posts.update(values_pre_page)
		self.generate('main_sidebar_base.html',values_posts)

class timedate(BaseRequestHandler):
	def get(self):
		month_year = self.request.path[1:-14]
		bookmark_id = self.request.get('b')
		if bookmark_id:
			bookmark_time_date = models.Article.get_by_id(int(bookmark_id)).time_date
			articles = models.Article.all().filter('month_year =',month_year).filter('article_type','article').order('-time_date').filter('time_date <=',bookmark_time_date).fetch(limit=self.settings['count_per_page']+1)
			pre_articles = models.Article.all().filter('month_year',month_year).filter('article_type','article').order('time_date').filter('time_date >',bookmark_time_date).fetch(limit=self.settings['count_per_page'])
		else:
			articles = models.Article.all().filter('month_year =',month_year).filter('article_type','article').order('-time_date').fetch(limit=self.settings['count_per_page']+1)
			pre_articles = None
		for article in articles:
			article.key_id = article.key().id()
			article.time_date_g = datetime.strftime(article.time_date,'%A %H:%M:%S %m月%d日 %Y年') #格式化帖子的发表时间
			#帖子的分类
			cate_list = []
			for cat_key in article.categories_keys:
				cate_list.append(db.get(cat_key))
			article.category = cate_list
			#帖子的分类 END
		values_posts={
			'articles': articles[:self.settings['count_per_page']],
			'path': self.request.path,
			'month_year_g': month_year+' 年'
		}
		if len(articles) == self.settings['count_per_page']+1:
			values_page = {
				'next_page': articles[self.settings['count_per_page']]
			}
			values_posts.update(values_page)
		if (pre_articles) and (len(pre_articles)>0):
			values_pre_page = {
				'pre_page': pre_articles[-1]
			}
			values_posts.update(values_pre_page)
		self.generate('main_sidebar_base.html',values_posts)

class show_image(webapp.RequestHandler):
	def get(self):
		img_path = self.request.path
		img_str_id =  img_path[1:-6]
		image = models.Image.get_by_id(int(img_str_id))
		self.response.headers['Content-Type'] = 'image/png'
		self.response.out.write(image.content)

class ArticleAtom(BaseRequestHandler):
	def get(self):
		articles = memcache_def.get_article_atom_memcache()
		value = {
			'updated': articles[0].time_date,
			'articles': articles,
			'url': self.request.uri
		}
		self.generate('article_atom.xml', value)

class CateArticleAtom(BaseRequestHandler):
	def get(self):
		str_list = self.request.path[1:-17]
		cate_list = str_list.split('_')
		for i in range(0,len(cate_list)):
			cate_list[i] = models.Category.get_by_id(int(cate_list[i])).key()
		articles = models.Article.all().filter('categories_keys in',cate_list).filter('article_type','article').order('-time_date').fetch(limit=10)
		value = {
			'updated': articles[0].time_date,
			'articles': articles,
			'url': self.request.uri
		}
		self.generate('article_atom.xml',value)

class SelectAtom(BaseRequestHandler):
	def get(self):
		self.generate('selectatom_sidebar_base.html')
	def post(self):
		cate_list = self.request.get_all('cate_list')
		str_list = ''
		for cate in cate_list:
			str_list += (cate+'_')
		self.redirect('/'+str_list+'article_atom.xml')

class CommentAtom(BaseRequestHandler):
	def get(self):
		comments = memcache_def.get_comment_atom_memcache()
		value = {
			'updated': comments[0].time_date,
			'comments': comments,
			'url': self.request.uri
		}
		self.generate('comment_atom.xml', value)

class error_base(BaseRequestHandler):
	def get(self,value=None):
		value = {'error': 'error:not fount the page! &nbsp; 错误：未找到此页面！'}
		self.generate('error_base.html', value)
	def post(self,value=None):
		value = {'error': 'error:not fount the page! &nbsp; 错误：未找到此页面！'}
		self.generate('error_base.html', value)

def main():
	application = webapp.WSGIApplication([
		('/$', default),
		('/article_atom.xml$', ArticleAtom),
		('/comment_atom.xml$', CommentAtom),
		('/.*_article_atom.xml$', CateArticleAtom),
		('/selectatom.html$', SelectAtom),
		('/.*article.html$', article),
		('/.*category.html$', category),
		('/.*timedate.html$',timedate),
		('/.*.image$',show_image),
		('/(.*)', error_base)
	],debug=True)
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
